package com.blt.govdata.controller.base;


import com.blt.govdata.core.constants.Constants;
import com.blt.govdata.core.web.TokenException;
import com.blt.govdata.model.TLog;
import com.blt.govdata.service.ITLogService;
import com.blt.govdata.utils.DESPlus;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by GongJun on 2018.03.27.
 */
public class BaseController {

    protected HttpServletRequest request;
    protected HttpServletResponse response;
    protected HttpSession session;
    protected String username;
    protected Integer userid;
    /**
     * 操作日志记录
     */
    @Autowired
    ITLogService service;

    @ModelAttribute
    public void setReqAndResp(HttpServletRequest request, HttpServletResponse response) throws Exception {
        this.request = request;
        this.response = response;
        this.session = request.getSession();
        if (!"OPTIONS".equals(request.getMethod())) {
            String token = request.getHeader(Constants.TOKEN);
            if (null != token) {
                token = token.replaceFirst("Bearer ", "");
                String ss = new DESPlus().decode(token);
                String[] userInfo = ss.split(",");
                if (userInfo.length == 4) {
                    this.userid = Integer.valueOf(userInfo[1]);
                    this.username = userInfo[2];
                }
            }
        }

        /**
         * 前端开发使用的VUE，后端使用的java，前后端分离，因为跨域问题JSESSIONID每次请求都会变化，解决方法如下：
         * 前端要将withCredentials设为true
         * 以ajax请求为例：
         *
         $.ajax({
         url: a_cross_domain_url,
         // 将XHR对象的withCredentials设为true
         xhrFields: {
         withCredentials: true
         }
         });
         *
         * Access-Control-Allow-Credentials 设为true的话，Access-Control-Allow-Origin就不能设为*了，只好改成具体的域了，这样就可以多次请求取到的sessionid就一致了。
         * */

    }

    @InitBinder
    protected void initBinder(WebDataBinder binder) {
        binder.registerCustomEditor(Date.class, new CustomDateEditor(
                new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"), true));
        binder.registerCustomEditor(Date.class, new CustomDateEditor(
                new SimpleDateFormat("yyyy-MM-dd"), true));
    }

    /**
     * 写入用户操作日志
     */
    protected void log(String oprate, String status) {
        String userName = (String) session.getAttribute(Constants.CURRENT_USERNAME);
        String uri = request.getRequestURI();
        TLog log = BeanUtils.instantiate(TLog.class);
        log.setUsername(userName);
        log.setPath(uri);
        log.setTime(BeanUtils.instantiate(Date.class));
        log.setOperate(oprate);
        log.setStatus(status);
        this.service.insert(log);
    }
}
